package com.start.shop.api.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.start.shop.api.param.goods.AddGoodsParam;
import com.start.shop.api.param.goods.DetailParam;
import com.start.shop.api.param.goods.GetAllGoodsByTypeParam;
import com.start.shop.api.param.goods.GetAllSkuByGoodsId;
import com.start.shop.api.param.goods.GetGoodsByIdParam;
import com.start.shop.api.param.goods.GetSkuByIdParam;
import com.start.shop.api.vo.goods.DetailVo;
import com.start.shop.api.vo.goods.GetAllGoodsByTypeVo;
import com.start.shop.api.vo.goods.GoodsItemVo;
import com.start.shop.api.vo.goods.GoodsVo;
import com.start.shop.api.vo.goods.IndexVo;
import com.start.shop.api.vo.goods.SkuAttrVo;
import com.start.shop.api.vo.goods.SkuVo;
import com.start.shop.common.constant.MsgObject;
import com.start.shop.common.constant.RspCode;
import com.start.shop.common.exception.MyException;
import com.start.shop.modules.repository.entity.Goods;
import com.start.shop.modules.repository.entity.GoodsType;
import com.start.shop.modules.repository.entity.Sku;
import com.start.shop.modules.repository.entity.SkuAttr;
import com.start.shop.modules.repository.entity.User;
import com.start.shop.modules.service.IGoodsService;
import com.start.shop.modules.service.ISkuService;
import com.start.shop.modules.service.IUserService;

import lombok.extern.slf4j.Slf4j;

/**
 * Title: ${file_name}
 * Description:
 * Copyright: Copyright (c) 2020
 * Company: www.parpur.com
 */

@Slf4j
@RestController
@RequestMapping(value = "/api")
public class GoodsCtroller {

    @Autowired
    IGoodsService goodsService;
    
    @Autowired
    ISkuService skuService;
    
    @Autowired
    IUserService userService;

    /**
     *  根据商品Id查询商品信息
     * @return
     */

    @RequestMapping(value = "/v1/getGoodsById")
    public ResponseEntity<MsgObject> getGoodsById(@RequestBody GetGoodsByIdParam getGoodsByIdParam) {
        //查询商品信息
        Goods goods = goodsService.getGoodsByGoodsId(getGoodsByIdParam.getGoodsId());
        if (goods == null) {
			throw new MyException(RspCode.GOODS_NOT_FOUND);
		}

        //返回结果
        GoodsItemVo goodsItemVo = GoodsItemVo.setdata(goods);
        return ResponseEntity.ok(MsgObject.success(goodsItemVo));
    }

    @RequestMapping(value = "/user/login")
    public ResponseEntity<MsgObject> LoginAuthenticator() {
    	log.info("loginParm:{}", "123");
    	return ResponseEntity.ok(MsgObject.success("123"));
    	
    }
    
    /**
     *  根据商品Id查询商品信息
     * @return
     */

    @RequestMapping(value = "/v1/getSkuById")
    public ResponseEntity<MsgObject> getSkuById(@RequestBody GetSkuByIdParam getSkuByIdParam) {
        //查询商品信息
        Sku sku = skuService.getSkuBySkuId(getSkuByIdParam.getSkuId());
        if (sku == null) {
			throw new MyException(RspCode.GOODS_NOT_FOUND);
		}

        //返回结果
        SkuVo goodsItemVo = SkuVo.setData(sku);
        
        return ResponseEntity.ok(MsgObject.success(goodsItemVo));
    }
    
    /**
     *  查询商品下的所有的Sku
     * @return
     */

    @RequestMapping(value = "/v1/getAllSkuByGoodsId")
    public ResponseEntity<MsgObject> getAllSkuByGoodsId(@RequestBody GetAllSkuByGoodsId getAllSkuByGoodsIdParam) {
        //查询商品信息
        List<Sku> skuList = skuService.getAllSkuByGoodsId(getAllSkuByGoodsIdParam.getGoodsId());
        if (skuList == null) {
			throw new MyException(RspCode.GOODS_NOT_FOUND);
		}
       
        List<SkuVo> skuVoList = new ArrayList<SkuVo>();
        for (int i = 0; i < skuList.size(); i++) {
        	 //返回结果
            SkuVo skuVo = SkuVo.setData(skuList.get(i));
            skuVoList.add(skuVo);
		}
       
        return ResponseEntity.ok(MsgObject.success(skuVoList));
    }
    
    /**
     *  查询商品的所有类型
     * @return
     */

    @RequestMapping(value = "/v1/getAllGoodsType")
    public ResponseEntity<MsgObject> getAllGoodsType() {
       List<GoodsType> goodsTypeList = goodsService.getAllGoodsType();
       return ResponseEntity.ok(MsgObject.success(goodsTypeList));
    }
    
    /**
     *  查询某类型的商品
     * @return
     */

    @RequestMapping(value = "/v1/getAllGoodsByType")
    public ResponseEntity<MsgObject> getAllGoodsByType(@RequestBody GetAllGoodsByTypeParam getAllGoodsByTypeParam) {
    	//根据类型获取商城类商品信息
    	List<Goods> goodsPage = goodsService.getAllGoodsByTypeId(getAllGoodsByTypeParam.getGoodsType());
       
    	//将PageInfo<Goods>换成输出商品返回数据格式
		List<GoodsVo> goodsVoList = new ArrayList<GoodsVo>();
		for(Goods goods : goodsPage) {
			List<Sku> skuList = skuService.getAllSkuByGoodsId(goods.getGoodsId());
			GoodsVo goodsVo = GoodsVo.setdata(goods, skuList);
			goodsVoList.add(goodsVo);
		}
		//组织返回报文
    	GetAllGoodsByTypeVo getAllGoodsByTypeVo = new GetAllGoodsByTypeVo(goodsVoList);

    	//返回
    	return ResponseEntity.ok(MsgObject.success(getAllGoodsByTypeVo));
    }
    

    @RequestMapping(value = "/v1/index")
	public ResponseEntity<MsgObject> index() {
		// 查询所有的商品类型
		List<GoodsType> goodsTypeList = goodsService.getAllGoodsType();

		List<IndexVo> indexVoList = new ArrayList<IndexVo>();

		for (int i = 0; i < goodsTypeList.size(); i++) {
			// 查找该类型的商品
			List<Goods> goodsList = goodsService.getAllGoodsByTypeId(goodsTypeList.get(i).getId());

			// 组织返回数据
			IndexVo indexVo = IndexVo.setData(goodsTypeList.get(i).getTypeId(), goodsTypeList.get(i).getTypeName(),
					goodsList);

			indexVoList.add(i, indexVo);
		}

		return ResponseEntity.ok(MsgObject.success(indexVoList));
	}
    
    
    /**
	 * showdoc
	 *
	 * @catalog 服务功能/商城服务
	 * @title 商城详情查询(detail)
	 * @description 商品详情查询
	 * @method post
	 * @url https://www.parpur.com/shop/v1/detail
	 * @param goodsId true int 商品编号
	 * @return {"code":"错误码","msg":"错误描述", "data":DetailVo}
	 * @return_param code string 错误码
	 * @return_param msg string 错误描述
	 * @return_param data DetailVo 详情对象
	 * @remark ```DetailVo:{goodsId:xxx, goodsType:xxx, goodsName:xxx, goodsTitle:xxx, goodsImg:xxx, bannerImg:[], goodsDesc:[], buyLimit:xx, skuList:[]}```
	 * @number 2
	 */

	@RequestMapping(value = "/v1/detail")
	public ResponseEntity<MsgObject> detail(@RequestBody @Valid DetailParam detailParm) {
		//检查用户是否已经有代理
//		User user=userService.getUserById(detailParm.getUser().getUserId());
//		if(detailParm.getAgentId()>0&&detailParm.getUser()!=null&&user.getAgentId()==0) {
//			userService.setUserAgent(detailParm.getUser().getUserId(), detailParm.getAgentId());
//		}
//		else {
//			log.info("不需要设置代理ID，用户代理为【{}】", detailParm.getAgentId());
//		}
		//商品查询
		Goods goods = goodsService.getGoodsByGoodsId(detailParm.getGoodsId());
		if(goods == null) {
			log.error("未找到该商品信息，goodsId【{}】", detailParm.getGoodsId());
            return ResponseEntity.ok(MsgObject.fail(RspCode.GOODS_NOT_FOUND.getCode(), RspCode.GOODS_NOT_FOUND.getMessage()));
        }
		
		//查询商品下的suk
		List<Sku> skuList = skuService.getAllSkuByGoodsId(detailParm.getGoodsId());
		
		List<String> goodsAttrList = Arrays.asList(goods.getGoodsAttr().split(","));
		
		log.info("{}",goods.getGoodsAttr());
		List<SkuAttrVo> skuAttrVos= new ArrayList<SkuAttrVo>();
		for (int i = 0; i < goodsAttrList.size(); i++) {
			//获取属性key
			log.info("{}",goodsAttrList.get(i));
			SkuAttr key=skuService.getSkuAttrById(Integer.valueOf(goodsAttrList.get(i).toString()));			
			List<SkuAttr> value=skuService.getSkuAttrByPid(key.getId());
			
			SkuAttrVo skuAttrVo= SkuAttrVo.setData(key, value);
			skuAttrVos.add(skuAttrVo);
		}
		
		//转换返回商品数据格式
		GoodsVo goodsVo = GoodsVo.setdata(goods,skuList);
		
		//转换返回商品Sku数据格式
		List<SkuVo> skuVoList = new ArrayList<SkuVo>();
		for(Sku sku : skuList) {
			//List<SkuAttr> skuAttrList= skuService.getSkuAttrById(sku.getSkuId());
			SkuVo skuVo = SkuVo.setData(sku);
			skuVoList.add(skuVo);
		}
		
		// 组织返回报文
		DetailVo detailVo = new DetailVo(goodsVo, skuVoList, skuAttrVos);
		return ResponseEntity.ok(MsgObject.success(detailVo));
	}
	
	@RequestMapping(value = "/v1/addGoods")
	public ResponseEntity<MsgObject> addGoods(@RequestBody @Valid AddGoodsParam addGoodsParm) {
		//插入到skuAttr表

		List<String> list = new ArrayList<String>();
		list.add("颜色");
		list.add("内存");
		List<String> valueList = new ArrayList<String>();
		valueList.add("红色,黑色");
		valueList.add("16G,32G");
		log.info("addGoods");
		//插入到sku  attr关系表
		//for (Sku sku : addGoodsParm.getSkuList()) {
		String properties = "1:1;2:1";
		List<String> propertyList = Arrays.asList(properties.split(";"));
		for (String property : propertyList) {
			int key = Integer.valueOf(Arrays.asList(property.split(":")).get(0));
			int value = Integer.valueOf(Arrays.asList(property.split(":")).get(1));
			String keyStr = list.get(key-1);
			String valueStr = Arrays.asList(valueList.get(key-1).split(",")).get(value-1);
			log.info("【{}】【{}】", keyStr, valueStr);
		}
		//}
		
		return null;
	}
	
    
}
